﻿
//
//  Copyright (c) 2011 Extreme: Paweł Huryn (lead), Jakub Domański
//

using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Extreme.SPFramework.DomainModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace Extreme.SPFramework.WebControls
{
    /// <summary>
    /// Renders as label in Disabled mode
    /// </summary>
    public class CustomPeopleEditor : PeopleEditor
    {
        [Browsable(true)]
        [Category("Appearance")]
        [Description("Renders control as string if disabled")]
        public bool RenderAsStringIfDisabled { get; set; }


        public List<PersonInfo> RecognizedPeople
        {
            get
            {
                return GetListOfPernsonInfo();
            }
        }
    
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (this.Enabled || !RenderAsStringIfDisabled)
                base.Render(writer);
            else
            {
                var content = new StringBuilder();
                foreach (PickerEntity entity in base.ResolvedEntities)
                {
                    content.Append(entity.DisplayText);
                    content.Append(base.EntitySeparator.ToString());
                    content.Append(" ");
                }
                writer.Write(content.ToString().TrimEnd(base.EntitySeparator, ' '));
            }
        }
        private PersonInfo GetCurrentAccountByLogin(SPWeb web, string loginName)
        {

            string userLogin = string.Empty;
            SPUser user = null;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                try
                {
                    using (SPSite site = new SPSite(web.Url))
                    {
                        using (SPWeb web2 = site.OpenWeb())
                        {
                            bool reachedMaxCount = false;
                            var users = SPUtility.SearchPrincipals(web2, loginName, SPPrincipalType.All, SPPrincipalSource.All, null, 100, out reachedMaxCount);
                            foreach (SPPrincipalInfo userInfo in users)
                            {
                                if (userInfo == null)
                                    continue;
                                if (!string.IsNullOrEmpty(userInfo.Email) && userInfo.LoginName.ToLower() == loginName.ToLower())
                                {
                                   
                                    user = web.EnsureUser(loginName);
                                    break;
                                }
                            }
                            if (user == null && users.Count > 0)
                            {
                                foreach (SPPrincipalInfo userInfo in users)
                                {
                                    if (userInfo == null)
                                        continue;
                                    if (userInfo.LoginName.ToLower() == loginName.ToLower())
                                    {
                                        user = web.EnsureUser(userInfo.LoginName);
                                        break;
                                    }
                                }
                            }
                        }
                    }


                }
                catch { }
            }
            );
            if (user != null)
                return new PersonInfo(user.ID, string.Empty, user.LoginName, user.Name, user.Email);
            else
                return null;
        }
        private List<PersonInfo> GetListOfPernsonInfo()
        {
            var output = new List<PersonInfo>();
            string loginName = string.Empty;
            foreach (PickerEntity entity in base.ResolvedEntities)
            {
                if (entity.IsResolved)
                {
                    loginName = entity.Key.ToString();
                    if (!string.IsNullOrEmpty(loginName))
                    {
                        var personInfo = GetCurrentAccountByLogin(SPContext.Current.Web, loginName);
                        if (personInfo != null)
                        {
                            var hrID = string.Empty;
                            try
                            {
                                hrID = entity.EntityData["HrId"].ToString();

                            }
                            catch{}
                            
                            personInfo.HrID = hrID;

                            output.Add(personInfo);
                        }
                            
                    }
                }
            }
            return output;
        }



    }
}
